import React, { memo, useState, useEffect } from 'react'
import { Tree, Spin, Icon } from 'antd'
import { http } from '@/lib'
import apis from '@/apis'
import { deepLoopFormateTree } from '@/utils/methods'
import './style.scss'

const OrgTree = (props: IOrgTreeProps) => {
  const { onSelect, defaultSelectedKeys } = props
  const [treeData, setTreeData] = useState<any>([])
  const [querying, setQuerying] = useState(false)
  const [expandedKeys, setExpandedKeys] = useState([])

  useEffect(() => {
    setQuerying(true)
    http.get(apis.OrganizationTreeByUser).then(res => {
      const data = [res.data]
      const treeData = deepLoopFormateTree({datas: data, originKey: { value: 'code', title: 'name', children: 'children' }})
      const expandedKeys = getExpandedKeys(treeData, defaultSelectedKeys)
      console.log(expandedKeys)
      setTreeData(treeData)
      setExpandedKeys(expandedKeys)
    }).finally(() => {
      setQuerying(false)
    })
  }, [])

  const onExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
  }

  return (
    <Spin spinning={querying}>
      <Tree
        className='internal-staff-tree'
        showLine
        treeData={treeData}
        onSelect={onSelect}
        defaultSelectedKeys={defaultSelectedKeys}
        expandedKeys={expandedKeys}
        onExpand={onExpand}
      />
    </Spin>
  )
}

export default memo(OrgTree)

interface IOrgTreeProps {
  onSelect: (e: any) => void
  defaultSelectedKeys?: string[]
}

function getExpandedKeys(nodesSource, keys) {
  let parentKeys = []
  if ((!Array.isArray(nodesSource) || nodesSource.length == 0) || (!Array.isArray(keys) || keys.length == 0)) {
    return parentKeys
  }
  const originKey = {value: 'value', children: 'children'}
  const loop = (nodes, keys) => {
    for (const key in nodes) {
      let children = nodes[key][originKey.children]
      if (children.some(item => keys.includes(item[originKey.value])) && !parentKeys.includes(nodes[key][originKey.value])) {
        // 保存找到的key
        let nodeKey = nodes[key][originKey.value]
        parentKeys.push(nodeKey)
        // 如果children里找到了选中的数据，则将当前节点的key作为选中数据，继续在整个tree节点数据里获取父级的key
        loop(nodesSource, [nodeKey])
      } else if (children && !parentKeys.includes(nodes[key][originKey.value])) {
        // 如果children里没有找到选中的数据，则继续往children里的children去找
        loop(children, keys)
      }
    }
  }
  loop(nodesSource, keys)
  return parentKeys
}
